package com.lb.jwitter.action.util;
import java.util.*;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.test.context.ContextConfiguration;

import com.lb.jwitter.service.ConditionReport;
import com.lb.jwitter.service.TblTaiKhoan;
import com.lb.jwitter.service.TblTaiKhoanService;
import com.lb.jwitter.util.ApplicationContextProvider;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;

@ContextConfiguration(locations="classpath:beans.xml")
public class LoginAction
{
	
	private String username;
	
	private String password;
	
	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}
	
	TblTaiKhoanService tblTaiKhoanService;
	
	 @Autowired // Injected by Spring when bean is "ready"
	 ApplicationContextProvider contextProvider;

public String execute() throws Exception
{
   	try{
   
       
       Map session = ActionContext.getContext().getSession();
       if(session.get("taiKhoan") != null) return Action.SUCCESS;

   	   session.put("taiKhoan", null);

	   	List<ConditionReport> cons = new ArrayList<ConditionReport>(); 
	    if(username!= null && !username.equalsIgnoreCase("")){ 
	        ConditionReport con = new ConditionReport(); 
	        con.setCol("username");
	        con.setValue1(username);
	        con.setOperator("eq");
	        cons.add(con);	
	    } else 
	    	return "noprivilege";
	    if(password!= null && !password.equalsIgnoreCase("")){ 
	        ConditionReport con = new ConditionReport(); 
	        con.setCol("password");
	        con.setValue1(password);
	        con.setOperator("eq");
	        cons.add(con);	
	    } else
	    	return "noprivilege";

	    ApplicationContext context = ApplicationContextProvider.getApplicationContext();

	   tblTaiKhoanService = (TblTaiKhoanService) context.getBean("tbl_TaiKhoanClient");
       List<TblTaiKhoan> taiKhoan = tblTaiKhoanService.findtblTaiKhoanByCondition(cons, 1, 1);

       if (taiKhoan == null || taiKhoan.size() == 0 ) return "noprivilege";
       
       session.put("taiKhoan", taiKhoan.get(0));
      
        return Action.SUCCESS;

     }
        catch(Exception e){
            System.out.println("Loi log in");
            e.printStackTrace();
            return Action.ERROR;
      }
       
}	
}
